import 'package:flutter/material.dart';
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'OneClass.dart';

class OneBuildPage extends StatefulWidget{
  var BuildName;
  OneBuildPage(String BuildName,{Key key}):super(key:key){
    this.BuildName = BuildName;
  }
  _OneBuildPageState createState() => _OneBuildPageState(BuildName);
}

class _OneBuildPageState extends State<OneBuildPage>{
  var ClassInf = List();
  var BuildName_CN;
  var BuildName_EN;
  var ShowNum;
  EasyRefreshController _controller;
  ScrollController _controller_scroll;
  bool showToTopBtn;

  _OneBuildPageState(String BuildName){
    this.BuildName_CN = BuildName;
    switch(BuildName){
      case '知明':{
        BuildName = 'ZM';
      }break;
      case '笃行':{
        BuildName = 'XD';
      }break;
      case '立诚':{
        BuildName = 'LC';
      }break;
      case '致广':{
        BuildName = 'ZG';
      }break;
    }
    this.BuildName_EN = BuildName;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = EasyRefreshController();
    _controller_scroll = ScrollController();
    showToTopBtn = false;
    ShowNum = 10;
    getDate();
    _controller_scroll.addListener(() {
      if(_controller_scroll.offset < 1000 && showToTopBtn){
        setState(() {
          this.showToTopBtn = false;
        });
      }
      else if(_controller_scroll.offset >= 1000 && !showToTopBtn){
        setState(() {
          this.showToTopBtn = true;
        });
      }
    });
  }

  void dispose(){
    super.dispose();
    _controller_scroll.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        leading: new IconButton(
          icon: new Icon(Icons.arrow_back_ios),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: Text('${this.BuildName_CN}'),
      ),
      body: EasyRefresh(
        controller: _controller,
        enableControlFinishRefresh: true,
        enableControlFinishLoad: true,
        firstRefresh: true,
        child:
          CustomScrollView(
            slivers: <Widget>[
              SliverFixedExtentList(
                delegate: SliverChildBuilderDelegate(
                    (context,index){
                      return this.ClassInf.length != 0 ?
                      CreateCard(
                          this.ClassInf[index]['Class'],
                          this.ClassInf[index]['MaxNum'],
                          this.ClassInf[index]['Num'],
                          this.ClassInf[index]['Percentage'])
                          :
                      InitialCard();
                    },
                  childCount: this.ShowNum
                ),
                itemExtent: 200,
              )
            ],
          ),
        onLoad: () async{
          await Future.delayed(Duration(seconds: 1),() {
            setState(() {
              this.ShowNum = ShowNum + 5 > this.ClassInf.length ? this.ClassInf.length : this.ShowNum + 5;
            });
            _controller.finishLoad();
          });
        },
        onRefresh: () async{
          await Future.delayed(Duration(seconds: 1), () {
            setState(() {
              getDate();
            });
            _controller.finishRefresh(success: true);
          });
        },
      ),
      floatingActionButton: !showToTopBtn ? null : FloatingActionButton(
          child: Icon(Icons.arrow_upward),
          onPressed: () {
            //返回到顶部时执行动画
            _controller_scroll.animateTo(.0,
                duration: Duration(milliseconds: 200),
                curve: Curves.ease
            );
          }
      ),
    );
  }

  Widget CreateCard(String ClassName,int MaxNum,int Num,var Percentage){
    return Card(
      elevation: 15.0,
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(14.0))),
      child: Column(
        children: [
          ListTile(
              title: Text('${ClassName}'),
              leading: Icon(
                Icons.school,
                color: Colors.blue,
              ),
              trailing: Icon(
                Icons.arrow_forward_ios,
              ),
              onTap: (){
                Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => OneClassPage(BuildName_CN, ClassName))
                );
              },
          ),
          Divider(),
          ListTile(
            title: Text('当前人数:${Num}  最大人数:${MaxNum}'),
            leading: Icon(
              Icons.people,
              color: Colors.blue,
            ),
          ),
          ListTile(
            title: Text('百分比:${Percentage}%'),
            leading: Icon(
              Icons.more_vert,
            ),
          )
        ],
      ),
    );
  }

  Widget InitialCard(){
    return Card(
      elevation: 15.0,
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(14.0))),
      child: Column(
        children: [
          ListTile(
              title: Text('请刷新~'),
              leading: Icon(
                Icons.school,
                color: Colors.blue,
              )
          ),
          Divider(),
          ListTile(
            title: Text(''),
            leading: Icon(
              Icons.people,
              color: Colors.blue,
            ),
          ),
          ListTile(
            title: Text('百分比: %'),
            leading: Icon(
              Icons.more_vert,
            ),
          )
        ],
      ),
    );
  }

  getDate() async{
    var url = 'https://www.fjnu-study.cn/request/inf_request.php?type=OneBuild&build=${this.BuildName_EN}';
    var response = await http.get(url);
    if(response.statusCode == 200){
      var jsonRes = convert.jsonDecode(response.body);
      if(jsonRes['BuildName'] == this.BuildName_EN){
        setState(() {
          this.ClassInf = jsonRes['Class'];
          this.ShowNum = ShowNum > this.ClassInf.length ? ClassInf.length : ShowNum;
        });
      }
    }
    else{
      print('请求错误，错误代码：${response.statusCode}');
    }
  }

}
